<?php
namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Session;
use think\Url;
use Zhuzhichao\IpLocationZh\Ip;

class Index extends Controller
{
    private static $score = 0;
    private static $info  = null;


    protected function _initialize()
    {
        header('Content-Type:text/html;charset=utf-8');

        //获取ip
//        $ip = $this->request->ip();
//        print_r(Ip::find("119.137.54.182"));die;

    }

    public function index2()
    {
        //查询题目
        $list = Db::name('problems')->order('rand()')->limit(1)->select();

        $single_list = $multiple_list = array();
        foreach ($list as $key => $value){
            $value['select'] = json_decode($value['select'],true);
            $value['answer'] = explode(',', $value['answer']);

            $single_list[] = $value;
        }
        $list_count = array('single_count'=>count($single_list),'multiple_count'=>count($multiple_list));
        //print_r($single_list);


        $this->assign("list_count",$list_count);

        $this->assign('single_list',$single_list);
        $this->assign('multiple_list',$multiple_list);
        return $this->fetch();
    }

    public function rankResult()
    {
//        if (self::$info == null) {
//            $this->redirect('index');
//        }else{
//            return $this->fetch('',self::$info);
//        }
        $data = Session::get('data');

        if (!$data) {
            $this->redirect('index');
        }else{
            return $this->fetch('', $data);
        }


    }


    public function index()
    {
        //获取并且删除数组
        if ( input('data') && $data = Cache::pull(input('data'))) {
            return $this->fetch('rankresult', $data);
        }
        //查询题目
        $list = Db::name('problems')->order('rand()')->limit(10)->select();

        $single_list = $multiple_list = array();
        foreach ($list as $key => $value){
            $value['select'] = json_decode($value['select'],true);
            $value['answer'] = explode(',', $value['answer']);

            $single_list[] = $value;
        }
        $list_count = array('single_count'=>count($single_list),'multiple_count'=>count($multiple_list));
        //print_r($single_list);


        $this->assign("list_count",$list_count);

        $this->assign('single_list',$single_list);
        $this->assign('multiple_list',$multiple_list);
        return $this->fetch('index2');
    }

    /**
     * @throws \Exception
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\HttpResponseException
     */
    public function saveData(){
        $data = $this->request->get();
        if (isset($data['data'])) {
            $data = json_decode($data['data'], 1);
            $query['mobile'] = $data['user_data']['mobile'];
            $query['adate'] = date('Y-m-d');
            $count = Db::name('answer')->where($query)->count();
            //答题超过三次不允许答题
            if ($count > 3) {
                $this->error("超过答题次数",'/index/index/index');
            }
            $user_info = $data['user_data'];
            $topic_list = array_filter($data['topic_data']);
            $id = array_keys($topic_list);
            $where['id'] = ['in', implode(',',$id)];
            $answers = Db::name('problems')->where($where)->field("id,answer,type")->select();
            foreach ($answers as $value) {
                if ($value['type'] == 1) {
                    //单选题
                    if ($topic_list[$value['id']] == $value['answer']) {
                        self::$score++;
                    }
                } else {
                    $arr = explode(',', $value['answer']);
                    sort($arr);
                    $arr2 = explode(',', $topic_list[$value['id']] );
                    sort($arr2);
                    //多选题
                    if ($arr == $arr2) {
                        self::$score++;
                    }
                }
            }
            //获取ip
            $ip = $this->request->ip();
            //根据IP查询地址
            //$ip = "123.125.71.38";
            $address = Ip::find($ip);

            $city_info = Db::name('city')->where('city', 'like', "{$address[1]}%")->find();
            //分数获取结束，储存数据
            $insert = ['username' => $user_info['username'], 'mobile' => $user_info['mobile'], 'company' => $user_info['company'], 'ip' => $ip, 'region' => $city_info['id'], 'score' => self::$score];
            $insert['adate'] = date("Y-m-d");
            $insert['atime'] = time();
            $res = Db::name('answer')->insertGetId($insert);
            $city_rank = 1;
            if ($res > 0) {
                //插入数据成功,统计数据+1
                Db::name('city')->where('id', $city_info['id'])->setInc('number', self::$score);
                //查询所有城市
                //该城市详情
                $city_list = Db::name('city')->select();
                foreach ($city_list as $key => $value) {
                    $city_lists[$key] = $value;
                    $rank[$key] = $value['number'];
                }
                array_multisort($rank, SORT_DESC, $city_lists, SORT_ASC);
                foreach ($city_list as $k => $v) {
                    if ($city_info['id'] == $value['id']) {
                        $city_rank = $k;
                    }
                }
                $info = array(
                    "number" => self::$score,
                    "score" => self::$score,
                    "city" => $city_info['city'],
                    "city_score" => $city_info['number']+ self::$score,
                    "city_lists" => $city_lists,
                    "city_rank"  => $city_rank,
                    "rank" => $res //第几个人
                );
                self::$info = $info;

                $params = $this->uniqidReal();

                cache($params, $info);

                return $this->redirect('index', ['data'=>$params]);
                //return $this->fetch('rankresult', $info);
            }
        }

    }

    /**
     * @param int $lenght
     * @return bool|string
     * @throws \Exception
     */
    private function uniqidReal($lenght = 13) {
        // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }

    public function checkjoin(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $query['mobile'] = $data['mobile'];
            $query['adate'] = date('Y-m-d');
            $count = Db::name('answer')->where($query)->count();
            //答题超过三次不允许答题
            if ($count>3){
                $this->error("超过答题次数");
            }else{
                $this->success("继续答题");
            }
        }
    }

}
